const https = require('https');

const { formatTime } = require('./util')

const SQLHelper = require('./SQLHelper')
//雪花算法生成id
const snowflake = require('./snowflake');

const multer = require('multer')
const storage = multer.diskStorage({
  destination: './uploads',
  filename: function (req, file, cb) {
    ///获取图片类型
    let fileType = file.originalname.split('.')
    fileType = fileType[fileType.length - 1]
    cb(null, snowflake() + '.' + fileType)
  }
})
const upload = multer({ storage: storage })


module.exports = function (app) {
  ///登录拦截中间件
  function loginRouter (req, res, next) {
    if (req.method == 'OPTIONS') {
      next()
      return;
    }
    let token = req.headers.token
    if (token) {
      SQLHelper(`select * from session where id = ${token} and state = 1`).then(ret => {
        if (ret.length) {
          let session = ret[0]
          ///2H
          if (new Date().getTime() - session.createTime < 2 * 60 * 60 * 1000) {
            req.session = {
              userId: session.userId,
              userName: session.userName
            }
            next()
          } else {
            res.status(400).send({ errorMsg: '登录超时' })
          }
        } else {
          res.status(400).send({ errorMsg: '当前用户未登录' })
        }
      })
    } else {
      res.status(400).send({ errorMsg: '缺少token，请先进行登录' })
    }
  }

  ///让初登录以外的所有小程序接口都需要进行先验证登录
  app.use('/admin', loginRouter)

  ///文件上传
  app.post('/upload', upload.single('file'), (req, res) => {
    res.send(req.file)
  })

  //管理后台登录
  app.post('/login', (req, res) => {
    let userName = req.body.userName
    let passWord = req.body.passWord
    if (userName && passWord) {
      SQLHelper(`
            select * from user where userName = '${userName}'
        `).then(users => {
        if (users.length) {///正常登陆
          let user = users[0]
          if (passWord == user.passWord) {
            let token = snowflake()
            //缓存到token到session表    
            SQLHelper(`
                INSERT INTO session(id,userId,userName,inTime,createTime,platform)
                VALUES(${token},'${user._id}','${user.nickName}','${formatTime(new Date())}',${new Date().getTime()},'admin')
                `).then(ret => {
              res.send({
                nickName: user.nickName,
                token,
                avatarUrl: user.photo,
                _id: user._id
              })
            })
          } else {
            res.send({ errorMsg: '密码错误' })
          }
        } else {
          res.send({ errorMsg: '当前用户不存在' })
        }
      })
    } else {
      res.send({ errorMsg: '用户名和密码不能为空' })
    }
  })

  ///退出登录
  app.get('/admin/logout', (req, res) => {
    SQLHelper(`
          update session set outTime = '${formatTime(new Date())}',state = 0 where id = '${req.headers.token}'`).then(ret => {
      res.send({ mag: '退出登录成功' })
    })
  })

  ///修改密码
  app.post('/admin/changePassWord', (req, res) => {
    let userId = req.session.userId
    let passWord = req.body.passWord
    let newPassWord = req.body.newPassWord
    if (passWord && newPassWord) {
      ///查询用户
      SQLHelper(`select passWord from user where _id = ${userId}`).then(users => {
        let user = users[0]
        ///比对原密码
        if (user.passWord == passWord) {
          //修改密码
          SQLHelper(`update user set passWord = '${newPassWord}' where _id = ${userId}`).then(ret => {
            res.send({ msg: '修改密码成功' })
          })
        } else {
          res.send({ errorMsg: '原密码错误' })
        }
      })
    } else {
      res.send({ errorMsg: '原密码和新密码不能为空' })
    }
  })

  ///分页获取首页项目列表
  ///PageSize 默认为10
  ///PageNum 当前页 默认1
  ///type 类型 非必填 banner,轮播图 category,分类 recommend,为你推荐 不填搜索全部
  app.get('/admin/index', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let title = req.query.title
    let whereSql = 'from banners where state = 1'
    ///按标题关键字搜索
    if (title) whereSql += ` and title like "%${title}%"`
    SQLHelper(`
    select count(*) as total ${whereSql};
    select * ${whereSql} 
    limit ${pageSize} offset ${offset}
    `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })


  ///新增轮播图
  ///img 图片地址 必填
  ///url 连接地址 非必填
  ///title 标题 轮播图不填，其他必填
  ///status 是否启用 非必填 1 启用，0 停用
  ///type 类型 非必填 banner(默认),轮播图 category,分类 recommend,为你推荐
  app.post('/admin/index', (req, res) => {
    let img = req.body.img, status = req.body.status
    let title = req.body.title
    if (!title) {
      res.send({ errorMsg: '标题不能为空' })
      return
    }
    if (status != 1) status = 0 //默认启用
    // if(status) status = 1
    if (img) {
      let createTime = new Date().getTime()
      SQLHelper(`
      INSERT INTO banners(title,img,status,state,createTime)
      VALUES('${title}','${img}','${status}',1,${createTime})
      `).then(ret => {
        // res.send(ret)
        let _id = ret.insertId
        res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  //修改首页项目
  //indexId 主码：_id 必填
  app.put('/admin/index', (req, res) => {
    if (req.body.indexId) {
      //需要修改的项
      let updateTime = new Date().getTime()
      let updateKey = ['img', 'url', 'title', 'status']
      let updateValues = [`updateTime=${updateTime}`]
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE banners set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  ///删除地址 逻辑删除
  //indexId 数据库中主码：_id 必填
  app.delete('/admin/index', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
        UPDATE banners
        set state = 0
        WHERE _id = ${indexId}
        `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  ///宠物

  ///分页获取品牌项目列表
  ///PageSize 默认为10
  ///PageNum 当前页 默认1
  app.get('/admin/productlist', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let title = req.query.title
    let type = req.query.type
    let whereSql = 'from medicine where state = 1'
    ///按类型查询
    if (type) whereSql += ` and type = '${type}'`
    ///按标题关键字搜索
    if (title) whereSql += ` and title like "%${title}%"`
    SQLHelper(`
    select count(*) as total ${whereSql};
    select * ${whereSql} 
    limit ${pageSize} offset ${offset}
    `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })

  ///新增首页项目
  ///img 品牌logo 非必填
  ///name 品牌名称 必填
  app.post('/admin/productlist', (req, res) => {
    let img = req.body.img
    let name = req.body.name
    if (!name) {
      res.send({ errorMsg: '品牌名称不能为空' })
      return
    }
    if (img) {
      let createTime = new Date().getTime()
      SQLHelper(`
      INSERT INTO medicine(name,img)
      VALUES('${name}','${img}')
      `).then(ret => {
        // res.send(ret)
        let _id = ret.insertId
        res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  //修改品牌管理项目
  app.put('/admin/productlist', (req, res) => {
    if (req.body.indexId) {
      //需要修改的项
      let updateTime = new Date().getTime()
      let updateKey = ['img', 'name']
      let updateValues = [`updateTime=${updateTime}`]
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE medicine set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  ///删除地址 逻辑删除
  //indexId 数据库中主码：_id 必填
  app.delete('/admin/productlist', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
        UPDATE medicine
        set state = 0
        WHERE _id = ${indexId}
        `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  ///玩具管理

  ///分页获取商品管理项目列表
  ///PageSize 默认为10
  ///PageNum 当前页 默认1
  app.get('/admin/product', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let name = req.query.name
    let whereSql = 'from toy where state = 1'
    ///按标题关键字搜索
    if (name) whereSql += ` and name like "%${name}%"`
    SQLHelper(`
    select count(*) as total ${whereSql};
    select * ${whereSql} 
    limit ${pageSize} offset ${offset}
    `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })
  ///新增首页项目
  app.post('/admin/product', (req, res) => {
    let imgs = req.body.imgs, sales = req.body.sales, status = req.body.status
    let name = req.body.name, brandId = req.body.brandId
    if (name) {
      res.send({ errorMsg: '标题不能为空' })
      return
    }
    if (imgs) {
      let createTime = new Date().getTime()
      SQLHelper(`
      INSERT INTO toy(name,imgs,status,brandId,sales,createTime,state)
      VALUES('${name}','${imgs}','${status}','${brandId}','${sales}','${createTime}',1)
      `).then(ret => {
        res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  //修改商品管理项目
  app.put('/admin/product', (req, res) => {
    if (req.body.indexId) {
      //需要修改的项
      let updateTime = new Date().getTime()
      let updateKey = ['name', 'brandId', 'imgs', 'sales', 'status']
      let updateValues = [`updateTime=${updateTime}`]
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE toy set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  ///删除商品 逻辑删除
  //indexId 数据库中主码：_id 必填
  app.delete('/admin/product', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
        UPDATE toy
        set state = 0
        WHERE _id = ${indexId}
        `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  ///新闻
  //分页获取新闻项目列表
  //pageSize 每页大小 默认10
  //pageNum 当前页 默认1
  app.get('/admin/news', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let title = req.query.title
    let whereSql = 'from videoos where state = 1'
    ///按标题关键字搜索
    if (title) whereSql += ` and title like "%${title}%"`
    SQLHelper(`
    select count(*) as total ${whereSql};
    select * ${whereSql} 
    limit ${pageSize} offset ${offset}
    `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })


  //新增新闻项目
  //img 图片地址 必填
  //title 标题
  //digest 摘要
  //time 时间
  //hot 热点
  //status 是否启用 非必填 1：启用 ； 0：停用
  app.post('/admin/news', (req, res) => {
    let img = req.body.img, title = req.body.title, digest = req.body.digest
    let time = req.body.time, hot = req.body.hot, status = req.body.status
    if (status != 1) status = 0 //默认启用
    if (img) {
      let createTime = new Date().getTime()
      SQLHelper(`
    INSERT INTO videoos(title,img,digest,time,hot,status,state,createTime,unitId)
    VALUES('${title}','${img}','${digest}','${time}','${hot}','${status}',1,${createTime},'juzao')
    `).then(ret => {
        res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  //修改新闻项目
  //indexId 主码_id 必填
  app.put('/admin/news', (req, res) => {
    if (req.body.indexId) {
      let updateTime = new Date().getTime()
      let updateKey = ['title', 'url', 'hot','state', 'status']
      let updateValues = []
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE videoos set ${updateValues.join(',')} WHERE id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  //删除首页项目
  //indexId 用户ID 必填
  app.delete('/admin/news', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
      UPDATE videoos
      set state = 0
      WHERE _id = ${indexId}
      `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  ///单品管理
  //分页获取单品项目列表
  //pageSize 每页大小 默认10
  //pageNum 当前页 默认1
  app.get('/admin/singleproduct', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let skuId = req.query.skuId
    let whereSql = 'from dog_detail where state = 1'
    ///按标题关键字搜索
    if (skuId) whereSql += ` and skuId like "%${skuId}%"`
    SQLHelper(`
    select count(*) as total ${whereSql};
    select * ${whereSql} 
    limit ${pageSize} offset ${offset}
    `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })


  //新增单品项目
  //skuId sku编码
  //salePrice 售价
  //originalPrice 原价
  //productName 商品名称
  //imgs 图片
  //props 属性
  //skuSpecification 直连供应商
  app.post('/admin/singleproduct', (req, res) => {
    let skuId = req.body.skuId, salePrice = req.body.salePrice, originalPrice = req.body.originalPrice
    let productName = req.body.productName, imgs = req.body.imgs, props = req.body.props
    if (imgs) {
      let createTime = new Date().getTime()
      SQLHelper(`
    INSERT INTO dog_detail(skuId,salePrice,originalPrice,productName,imgs,props,state,createTime,unitId)
    VALUES('${skuId}','${salePrice}','${originalPrice}','${productName}','${imgs}','${props}',1,${createTime},'juzao')
    `).then(ret => {
        res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  //修改单品项目
  //indexId 主码_id 必填
  app.put('/admin/singleproduct', (req, res) => {
    if (req.body.indexId) {
      let updateTime = new Date().getTime()
      let updateKey = ['skuId', 'salePrice', 'originalPrice', 'productName', 'imgs', 'props']
      let updateValues = [`updateTime=${updateTime}`]
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE dog_detail set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  //删除单品
  //indexId 用户ID 必填
  app.delete('/admin/singleproduct', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
      UPDATE dog_detail
      set state = 0
      WHERE _id = ${indexId}
      `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  ///为你推荐
  //分页获取新闻项目列表
  //pageSize 每页大小 默认10
  //pageNum 当前页 默认1
  app.get('/admin/recommend', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let title = req.query.title
    let whereSql = 'from recommand where state = 1'
    ///按标题关键字搜索
    if (title) whereSql += ` and title like "%${title}%"`
    SQLHelper(`
    select count(*) as total ${whereSql};
    select * ${whereSql} 
    limit ${pageSize} offset ${offset}
    `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })


  //新增新闻项目
  //img 图片地址 必填
  //title 标题
  //digest 摘要
  //time 时间
  //hot 热点
  //status 是否启用 非必填 1：启用 ； 0：停用
  app.post('/admin/recommend', (req, res) => {
    let img = req.body.img, title = req.body.title, digest = req.body.digest
    let time = req.body.time, hot = req.body.hot, status = req.body.status
    if (status != 1) status = 0 //默认启用
    if (img) {
      let createTime = new Date().getTime()
      SQLHelper(`
    INSERT INTO recommand(title,img,digest,time,hot,status,state,createTime,unitId)
    VALUES('${title}','${img}','${digest}','${time}','${hot}','${status}',1,${createTime},'juzao')
    `).then(ret => {
        res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  //修改新闻项目
  //indexId 主码_id 必填
  app.put('/admin/recommend', (req, res) => {
    if (req.body.indexId) {
      let updateTime = new Date().getTime()
      let updateKey = ['img', 'title', 'state', 'status']
      let updateValues = []
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE recommand set ${updateValues.join(',')} WHERE id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  //删除首页项目
  //indexId 用户ID 必填
  app.delete('/admin/recommend', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
      UPDATE recommand
      set state = 0
      WHERE _id = ${indexId}
      `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  ///领养寄养
  //分页获取新闻项目列表
  //pageSize 每页大小 默认10
  //pageNum 当前页 默认1
  app.get('/admin/information', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let title = req.query.title
    let whereSql = 'from information where state = 1'
    ///按标题关键字搜索
    if (title) whereSql += ` and title like "%${title}%"`
    SQLHelper(`
    select count(*) as total ${whereSql};
    select * ${whereSql} 
    limit ${pageSize} offset ${offset}
    `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })


  //新增新闻项目
  //img 图片地址 必填
  //title 标题
  //digest 摘要
  //time 时间
  //hot 热点
  //status 是否启用 非必填 1：启用 ； 0：停用
  app.post('/admin/information', (req, res) => {
    let img = req.body.img, title = req.body.title, digest = req.body.digest
    let time = req.body.time, hot = req.body.hot, status = req.body.status
    if (status != 1) status = 0 //默认启用
    if (img) {
      let createTime = new Date().getTime()
      SQLHelper(`
    INSERT INTO information(title,imgs,digest,time,hot,status,state,createTime,unitId)
    VALUES('${title}','${imgs}','${digest}','${time}','${hot}','${status}',1,${createTime},'juzao')
    `).then(ret => {
        res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  //修改新闻项目
  //indexId 主码_id 必填
  app.put('/admin/information', (req, res) => {
    if (req.body.indexId) {
      let updateTime = new Date().getTime()
      let updateKey = ['imgs', 'digest', 'title', 'time', 'hot', 'status']
      let updateValues = [`updateTime=${updateTime}`]
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE information set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  //删除首页项目
  //indexId 用户ID 必填
  app.delete('/admin/information', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
      UPDATE information
      set state = 0
      WHERE _id = ${indexId}
      `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  ///会员
  //分页获取会员信息
  //pageSize 每页大小 默认10
  //pageNum 当前页 默认1
  app.get('/admin/vip', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let phone = req.query.phone
    let whereSql = 'from vip where state = 1'
    ///按标题关键字搜索
    if (phone) whereSql += ` and phone like "%${phone}%"`
    SQLHelper(`
      select count(*) as total ${whereSql};
      select * ${whereSql} 
      limit ${pageSize} offset ${offset}
      `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })

  //删除会员信息
  //indexId 用户ID 必填
  app.delete('/admin/vip', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
      UPDATE vip
      set state = 0
      WHERE id = ${indexId}
      `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  //新增会员信息
  //name 姓名
  //phone 电话号码
  //grade 开通等级
  //sex 性别
  //status 是否启用 非必填 1：启用 ； 0：停用
  app.post('/admin/vip', (req, res) => {
    let memberId = req.body.memberId,name = req.body.name, phone = req.body.phone, grade = req.body.grade
    let sex = req.body.sex, state = req.body.state,status = req.body.status
    if (status != 1) status = 0 //默认启用
    if (name) {
      SQLHelper(`
    INSERT INTO vip(memberId,name,phone,grade,sex,state,status)
    VALUES('${memberId}','${name}','${phone}','${grade}','${sex}',1,0)
    `).then(ret => {
        res.send(ret.insertId ? { id: ret.insertId } : { errorMsg: '新增数据失败' })
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  //修改会员项目
  //indexId 主码_id 必填
  app.put('/admin/vip', (req, res) => {
    if (req.body.indexId) {
      let updateTime = new Date().getTime()
      let updateKey = ['memberId', 'name', 'phone', 'grade','sex', 'state', 'status']
      let updateValues = []
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE vip set ${updateValues.join(',')} WHERE id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  
  ///收货地址address
  //分页获取地址信息
  //pageSize 每页大小 默认10
  //pageNum 当前页 默认1
  app.get('/admin/address', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let phone = req.query.phone
    let whereSql = 'from address where state = 1'
    ///按标题关键字搜索
    if (phone) whereSql += ` and phone like "%${phone}%"`
    SQLHelper(`
      select count(*) as total ${whereSql};
      select * ${whereSql} 
      limit ${pageSize} offset ${offset}
      `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })

  //删除收货地址
  //indexId 用户ID 必填
  app.delete('/admin/address', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
      UPDATE address
      set state = 0
      WHERE _id = ${indexId}
      `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  ///优惠券发放
  //分页获取优惠券信息
  //pageSize 每页大小 默认10
  //pageNum 当前页 默认1
  app.get('/admin/coupon', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let num = req.query.num
    let whereSql = 'from money where state = 1'
    ///按标题关键字搜索
    if (num) whereSql += ` and num like "%${num}%"`
    SQLHelper(`
      select count(*) as total ${whereSql};
      select * ${whereSql} 
      limit ${pageSize} offset ${offset}
      `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })

  //删除优惠券信息
  //indexId 用户ID 必填
  app.delete('/admin/coupon', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
      UPDATE money
      set state = 0
      WHERE id = ${indexId}
      `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  //修改优惠券
  //indexId 主码_id 必填
  app.put('/admin/coupon', (req, res) => {
    if (req.body.indexId) {
      let updateTime = new Date().getTime()
      let updateKey = ['num', 'title',  'state', 'status']
      let updateValues = []
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE money set ${updateValues.join(',')} WHERE id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

}



